package dk.hojlind.hackhunt.model;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import dk.hojlind.hackhunt.control.ServerHandler;

public class ServerService implements Runnable, Subject, Observer {

    private int portNumber;
    private ArrayList observers;
    private String message;
    
    /**
     * default constructor
     */
    public ServerService()
    {
    	observers = new ArrayList();
    }
    
    /**
     * constructor
     * @param portNumber the port to listen on
     */
    public ServerService(int portNumber)
    {
        this.portNumber = portNumber;
        observers = new ArrayList();
    }
	
	
    /**
     * start the server
     * Listen for connections, establishes and receives the request from the clients and returns the reply
     */
    public void run() 
    {
        try 
        {
            ServerSocket serverSocket = new ServerSocket(portNumber);
            Socket server;
            int i = 0;
            int maxConnections = 0;
            while((i++ < maxConnections) || (maxConnections == 0))
            {
                server = serverSocket.accept();
                ServerHandler connection= new ServerHandler(server);
                connection.registerObserver(this);
                Thread t = new Thread(connection);
                t.start();
                
            }
        } 
        catch (IOException ex) 
        {
            Logger.getLogger(ServerService.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
	public void registerObserver(Observer observer) {
		observers.add(observer);
	}

	@Override
	public void unRegisterObserver(Observer observer) {
		int i = observers.indexOf(observer);
		if(i >= 0)
		{
			observers.remove(i);
		}
	}

	@Override
	public void notifyObservers() {
		for (int i = 0; i < observers.size(); i++)
		{
			Observer holder = (Observer) observers.get(i);
			holder.update(message);
		}
	}

	@Override
	public void update(String message) {
		this.message = message;
		notifyObservers();
		
	}
}
